import { log } from "cc";
import { EventMgr } from "../../Managers/EventMgr";
import { Globle } from "../Globle";
export default class WebSocketManager {
    private static _instance: WebSocketManager;

    public static get instance(): WebSocketManager {
        if (this._instance == null) {
            this._instance = new WebSocketManager();
        }
        return this._instance;
    }

    private connected: boolean = false;
    private ws: WebSocket;

    public event: EventTarget = new EventTarget();


    public connect() {
        if (this.ws && this.connected) {
            return;
        }
        this.ws = new WebSocket(Globle.wsURL);

        var that = this;

        this.ws.onopen = function () {
            console.log("connect sucess");
            that.connected = true;
            that.login();
        };

        this.ws.onerror = function () {
            console.log("ws error");
            that.connected = false;
        };

        this.ws.onclose = function () {
            console.log("connect faile");
            that.connected = false;
            // that.connect("", 0, "");
        };
        this.ws.onmessage = function (event) {
            // handleMsg(new Uint8Array(event.data));
            if (event.data) {
                var obj: any = JSON.parse(event.data);
                // console.log("返回的数据是",obj)
                EventMgr.Instance.Emit(obj.cmd, obj);
                console.log("ws message:" + event.data);
            }
        };
        setInterval(function (): void {
            console.log(that.connected);
            if (that.connected == false) {
                that.connect();
            } else {
                that.send({ c: "heart" })
            }
        }, 5000)
    }

    public send(data: any) {
        if (this.connect) {
            this.ws.send(JSON.stringify(data));
        } else {
            console.error("ws not connected");
        }

    }

    public closeWS() {
        // WebSocketManager.instance.event.on( WSCmd.CHALLENGE_RES , this.test , this )
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
    }
    public login() {
        this.send({
            "cmd": "login",
            "id": parseInt(Globle.userData.id),
            "nickName": Globle.userData.nickName,
            "avatar": Globle.userData.avatar
        });
    }

    //进入房间
    public enterRoom(roomId: number) {
        this.send({
            "cmd": "enterRoom",
            "roomId": roomId
        });
    }
    //退出房间
    public leaveRoom() {
        this.send({
            "cmd": "leaveRoom",
        });
    }
    //进入小房间
    public joinSmallRoom(smallRoomId: number) {
        this.send({
            "cmd": "joinSmallRoom",
            "smallRoomId": smallRoomId,//小房间数
        });
    }
}
